package com.artup.util.file;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.im4java.core.GMOperation;
import org.im4java.core.GraphicsMagickCmd;
import org.im4java.core.IM4JavaException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileHelper {
	private static final Logger LOGGER = LoggerFactory.getLogger(FileHelper.class);

	public static String getFileContent(String fileName) {

		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			File f = new File(fileName);

			reader = new BufferedReader(new FileReader(f));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileContent.toString();
	}

	public static String getFileContent(InputStream is) {

		BufferedReader reader = null;
		StringBuilder fileContent = new StringBuilder();
		try {
			reader = new BufferedReader(new InputStreamReader(is));
			String line = "";
			while ((line = reader.readLine()) != null) {
				fileContent.append(line);
				fileContent.append("\n");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (reader != null) {
					reader.close();
					reader = null;
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fileContent.toString();

	}

	public static boolean setFileContent(String path, String content) {
		boolean flag = false;
		DataOutputStream dos = null;
		try {
			if (content != null && content.length() >= 0) {
				byte abyte[] = content.getBytes();
				dos = new DataOutputStream(new FileOutputStream(path));
				dos.write(abyte, 0, abyte.length);
				dos.flush();

				flag = true;
			}
		} catch (FileNotFoundException e) {
			// log.error("fnfe:" + e);
		} catch (IOException e) {
			// log.error("ioe:" + e);
		} finally {
			if (dos != null) {
				try {
					dos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				dos = null;
			}
		}
		return flag;
	}
	/**
	 * 得到文件后缀名
	 * @param fileName
	 * @return
	 */
	public static String getFileExt(String fileName) {
		if (fileName == null)
			return "";

		String ext = "";
		int lastIndex = fileName.lastIndexOf(".");
		if (lastIndex >= 0) {
			ext = fileName.substring(lastIndex + 1).toLowerCase();
		}

		return ext;
	}

	
	/**
	 * 获得一个文件全路径中的文件名,排除路径信息
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 文件名
	 */
	public static String getFileName(String filePath) {
		if(filePath!=null){
			filePath = filePath.replace("\\", "/");
			if (filePath.indexOf("/") != -1) {
				return filePath.substring(filePath.lastIndexOf("/") + 1);
			}
			return filePath;
		}else
			return "";
	}
	
	public static String getFilePath(String filePath){
		if(filePath!=null){
			filePath = filePath.replace("\\", "/");
			if (filePath.indexOf("/") != -1) {
				return filePath.substring(0,filePath.lastIndexOf("/")+1);
			}
			return filePath;
		}else
			return "";
	}
	/**
	 * 获得一个文件名 排除扩展名
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 文件名
	 */
	public static String getFileName2(String filePath){
		String temp = getFileName(filePath);
		if (temp.indexOf(".") != -1) {
			return temp.substring(0,temp.lastIndexOf("."));
		}
		return temp;
	}
	/**
	 * 获得一个文件全路径中的文件名 排除扩展名
	 * 
	 * @param filePath
	 *            文件路径
	 * @return 文件名
	 */
	public static String getFilePathNotExt(String filePath){
		String temp = filePath;
		if (temp.indexOf(".") != -1) {
			return temp.substring(0,temp.lastIndexOf("."));
		}
		return temp;
	}
	
	public static String getFileNameNoExt(String filePath){
		if(StringUtils.isNotBlank(filePath)){
			if (filePath.indexOf(".") != -1) 
				return filePath.substring(0,filePath.lastIndexOf("."));
		}
		return null;
	}
	
	/** 
     * 创建文件夹 
     *  
     * @param strFilePath 
     *            文件夹路径 
     */  
    public boolean mkdirFolder(String strFilePath) {  
        boolean bFlag = false;  
        try {  
            File file = new File(strFilePath.toString());  
            if (!file.exists()) {  
                bFlag = file.mkdir();  
            }  
        } catch (Exception e) {  
            //logger.error("新建目录操作出错" + e.getLocalizedMessage());  
            e.printStackTrace();  
        }  
        return bFlag;  
    }
    

	/**
	 * 删除文件
	 * 
	 * @param files
	 */
	public static void deleteFile(File... files) {
		if (files == null) {
			return;
		}
		for (File f : files) {
			if (f.exists()) {
				f.delete();
			}
		}
	}

	/**
	 * 删除文件夹
	 * 
	 * @param files
	 *//*
	public static void deleteDirectory(File file) {
		if (file.exists()) { // 判断文件是否存在
			if (file.isFile()) { // 判断是否是文件
				file.delete(); // delete()方法 你应该知道 是删除的意思;
			} else if (file.isDirectory()) { // 否则如果它是一个目录
				File[] files = file.listFiles(); // 声明目录下所有的文件 files[];
				for (int i = 0; i < files.length; i++) { // 遍历目录下所有的文件
					deleteDirectory(files[i]); // 把每个文件 用这个方法进行迭代
				}
			}
			file.delete();
		} else {
			throw new SystemException("所删除的文件不存在！");
		}
	}*/

	/** 
     * 删除文件 
     *  
     * @param strFilePath 
     * @return 
     */  
    public static boolean removeFile(String strFilePath) {  
        boolean result = false;  
        if (strFilePath == null || "".equals(strFilePath)) {  
            return result;  
        }  
        File file = new File(strFilePath);  
        if (file.isFile() && file.exists()) {  
            result = file.delete();  
            if (result == Boolean.TRUE) {  
                //logger.debug("[REMOE_FILE:" + strFilePath + "删除成功!]");  
            } else {  
                //logger.debug("[REMOE_FILE:" + strFilePath + "删除失败]");  
            }  
        }  
        return result;  
    }  
  
	/**
	 * 移动目录
	 * @param srcFileList
	 * @param destDir
	 */
	public static void moveFile(List<File> srcFileList, String destDir) {
		int size = srcFileList.size();
		if (size > 0) {
			File destDirFile = new File(destDir);
			if (!destDirFile.exists()) {
				destDirFile.mkdirs();
			}

			File destFile = null;
			File srcFile = null;
			for (int i = 0; i < size; i++) {
				srcFile = srcFileList.get(i);
				destFile = new File(destDirFile, srcFile.getName());
				if (destFile.exists()) {
					destFile.delete();
				}
				srcFile.renameTo(new File(destDir, srcFile.getName()));
			}
		}
	}
	
	public static String replaceScanPath(String srcFilePath,String replacement){
		if(srcFilePath!=null){
			String temp = StringUtils.replace(srcFilePath,File.separator,"/");
			String filePath[] = StringUtils.splitByWholeSeparator(temp,replacement);
			return replacement+filePath[filePath.length-1];
		}else
			return null;
	}
	
	public static List<String> getSubFolderName(File parentFile){
		List<String> list = new ArrayList<String>();
		File[] files = parentFile.listFiles();
		if (files != null) {
			for(File file: files){
				if(file.isDirectory()){
					list.add(file.getName());
				}
			}
		}
		return list;
	}
	
	public static String getSubTxtName(File parentFile){
		String str = null;
		File[] files = parentFile.listFiles();
		if (files != null) {
			for(File file: files){
				if(file.isFile() && file.getName().toLowerCase().endsWith(".txt")){
					str = file.getAbsolutePath();
				}
			}
		}
		return str;
	}
	
	public static String getSubPicName(File parentFile){
		String str = null;
		File[] files = parentFile.listFiles();
		if (files != null) {
			for(File file: files){
				if(file.isFile() && file.getName().toLowerCase().endsWith(".jpg")){
					str = file.getAbsolutePath();
				}
			}
		}
		return str;
	}
	
	public static void generateImage(File file,Integer width,Integer height,String newPath) throws IOException,IM4JavaException, InterruptedException{
		//String artistsPath = PropertiesLoader.getProperty("system.artistsPath");
		GMOperation op = new GMOperation();
		GraphicsMagickCmd cmd = new GraphicsMagickCmd("convert");
		op.colorspace("RGB");
		op.density(72);
		//op.resize(width,height,'>');
		op.addRawArgs("-resize",width+"x"+ height +"!");
		op.quality(80.0);
		//op.addRawArgs("+profile","");
		op.p_profile("*");
		op.addImage(file.getAbsolutePath());
		//new File(path+CodeUtil.hashMod(getFileNameNoExt(file.getName()), 100)).mkdirs();
		op.addImage(newPath);
		//op.addRawArgs(arg0)
		cmd.run(op);
	}
	
	/**
	 * 复制文件
	 * @param s
	 * @param t
	 */
	public static void fileChannelCopy(File s, File t) {
		if(s.isDirectory()) {
			File[] flist = s.listFiles();
			t.mkdirs();
			for(File file : flist) {
				fileChannelCopy(file, new File(t.getPath() + "/" + file.getName()));
			}
		} else {
			FileInputStream fi = null;
		    FileOutputStream fo = null;
		    FileChannel in = null;
		    FileChannel out = null;
		    try {
		        fi = new FileInputStream(s);
		        fo = new FileOutputStream(t);
		        in = fi.getChannel();//得到对应的文件通道
		        out = fo.getChannel();//得到对应的文件通道
		        in.transferTo(0, in.size(), out);//连接两个通道，并且从in通道读取，然后写入out通道
		    } catch (IOException e) {
		        e.printStackTrace();
		    } finally {
		        try {
		            fi.close();
		            in.close();
		            fo.close();
		            out.close();
		        } catch (IOException e) {
		            e.printStackTrace();
		        }
		    }
		} 
    }
	
	/**
     * get postfix of the path
     * @param path
     * @return
     */
    public static String getPostfix(String path) {
        if (path == null || "".equals(path.trim())) {
            return "";
        }
        if (path.contains(".")) {
            return path.substring(path.lastIndexOf(".") + 1, path.length());
        }
        return "";
    }
    
    /**
     * 移动文件
     * @param srcFileList 源文件
     * @param destDir 新文件路径
     * @return
     */
	public static boolean moveFile(String srcFileList, String destDir) {
		File oldFile = new File(srcFileList); 
		//判断源文件是否存在
		if(!oldFile.exists()) 
			return false;
		File fnewpath = new File(destDir); 
		if(!fnewpath.exists()) 
			fnewpath.mkdirs();
		//将文件移到新文件里 
		File fnew = new File(destDir+oldFile.getName()); 
		oldFile.renameTo(fnew); 
		return true;
	}
    
	/**
	 * 获取文件大小
	 * @param filePath 文件路径
	 * @return
	 */
	public static long getFileSize(String filePath) {
		long size = 0;
		
		if(StringUtils.isBlank(filePath)) {
			return size;
		}
		
		File file = new File(filePath);
		
		if (!file.exists()) {
			return size;
        }
		
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(filePath);
		} catch (FileNotFoundException e) {
			LOGGER.error("未找到此文件！", e);
			
			return size;
		}
		
		BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
		
		try {
			size = bufferedInputStream.available();
		} catch (IOException e) {
			LOGGER.error("获取文件大小 - 失败！", e);
		}
		
		if (null != fileInputStream) {
			try {
				fileInputStream.close();
			} catch (IOException e) {
				LOGGER.error("关闭输入流 - 失败！", e);
				
				return size;
			}
		}
		
		return size;
	}
	
	public static void main(String[] args) {
//		moveFile("D:\\cs\\t.jpg","D:\\cs\\22\\");
		System.out.println(getFileSize("D:\\tmp\\original\\2017\\7\\25\\888\\e7a66335ffac4685a28611d0bdac1e7e.jpg"));
	}
}
